//
//  ChatDetailView.swift
//  WechatApp
//
//  Created on 2024.
//

import SwiftUI

struct ChatDetailView: View {
    let chat: Chat
    @State private var messages = Message.mockMessages
    @State private var inputText = ""
    @FocusState private var isInputFocused: Bool
    
    var body: some View {
        VStack(spacing: 0) {
            // Messages list
            ScrollViewReader { proxy in
                ScrollView {
                    LazyVStack(alignment: .leading, spacing: 8) {
                        ForEach(messages) { message in
                            MessageBubble(
                                message: message,
                                avatarUrl: message.isMe ? nil : chat.avatarUrl,
                                contactName: message.isMe ? nil : chat.name
                            )
                            .id(message.id)
                            .frame(maxWidth: .infinity, alignment: message.isMe ? .trailing : .leading)
                        }
                    }
                    .padding(.horizontal, 12)
                    .padding(.vertical, 8)
                }
                .onAppear {
                    scrollToBottom(proxy: proxy)
                }
                .onChange(of: messages.count) { _ in
                    scrollToBottom(proxy: proxy)
                }
            }
            
            // Input bar
            HStack(spacing: 8) {
                Button(action: {}) {
                    Image(systemName: "mic.fill")
                        .foregroundColor(.primary)
                }
                
                TextField("", text: $inputText, prompt: Text("输入消息"))
                    .textFieldStyle(.roundedBorder)
                    .focused($isInputFocused)
                    .onSubmit {
                        sendMessage()
                    }
                
                Button(action: {}) {
                    Image(systemName: "face.smiling")
                        .foregroundColor(.primary)
                }
                
                Button(action: {
                    if !inputText.isEmpty {
                        sendMessage()
                    }
                }) {
                    Image(systemName: "plus.circle.fill")
                        .foregroundColor(.primary)
                }
            }
            .padding()
            .background(Color(red: 0.97, green: 0.97, blue: 0.97))
        }
        .navigationTitle(chat.name)
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {}) {
                    Image(systemName: "ellipsis")
                }
            }
        }
    }
    
    private func sendMessage() {
        guard !inputText.trimmingCharacters(in: .whitespaces).isEmpty else { return }
        
        let newMessage = Message(
            content: inputText,
            type: .text,
            isMe: true,
            timestamp: Date()
        )
        
        messages.append(newMessage)
        inputText = ""
    }
    
    private func scrollToBottom(proxy: ScrollViewProxy) {
        if let lastMessage = messages.last {
            withAnimation {
                proxy.scrollTo(lastMessage.id, anchor: .bottom)
            }
        }
    }
}

struct MessageBubble: View {
    let message: Message
    let avatarUrl: String?
    let contactName: String?
    
    var body: some View {
        HStack(alignment: .top, spacing: 8) {
            if message.isMe {
                // 发送的消息：Spacer 在左边，将消息推到右边
                Spacer()
            } else {
                // 接收的消息：头像在左边
                NavigationLink(destination: ProfileView(name: contactName ?? "Contact", avatarUrl: avatarUrl)) {
                    if let avatarUrl = avatarUrl, let url = URL(string: avatarUrl) {
                        AsyncImage(url: url) { image in
                            image
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                        } placeholder: {
                            InitialsAvatar(contactName ?? "Contact", size: 40)
                        }
                        .frame(width: 40, height: 40)
                        .clipShape(RoundedRectangle(cornerRadius: 4))
                    } else {
                        InitialsAvatar(contactName ?? "Contact", size: 40)
                    }
                }
            }
            
            // Message bubble
            Text(message.content)
                .font(.system(size: 16))
                .foregroundColor(message.isMe ? .white : .primary)
                .padding(.horizontal, 12)
                .padding(.vertical, 8)
                .background(
                    message.isMe
                        ? Color(red: 0.18, green: 0.80, blue: 0.44) // WeChat green
                        : Color.white
                )
                .clipShape(RoundedRectangle(cornerRadius: 4))
        }
    }
}

#Preview {
    NavigationView {
        ChatDetailView(chat: Chat.mockChats[0])
    }
}

